package com.blb.ssm.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blb.ssm.controller.base.BaseController;
import com.blb.ssm.entity.Menu;
import com.blb.ssm.entity.RoleMenu;
import com.blb.ssm.entity.User;
import com.blb.ssm.entity.UserRole;
import com.blb.ssm.service.IMenuService;
import com.blb.ssm.service.IRoleMenuService;
import com.blb.ssm.service.IUserRoleService;
import com.blb.ssm.service.IUserService;

/**
 * 后台登录控制器
 * @author Administrator
 *
 */
@Controller
public class AdminLoginController extends BaseController{
	
	private Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private IMenuService menuService;
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private IUserRoleService userRoleService;
	
	@Autowired
	private IRoleMenuService roleMenuService;

	/**
	 * 登录
	 * @param user
	 * @param redirect
	 * @return
	 */
	@RequestMapping("/a/login")
	public String login(User user, RedirectAttributes redirect){
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
			return redirect("a/index");
		} catch (UnknownAccountException uae) {
			String msg = "账户["+ token.getPrincipal() + "]不存在";
            log.error(msg);
            redirect.addFlashAttribute(MSG, msg);
        } catch (IncorrectCredentialsException ice) {
            String msg = "账户["+ token.getPrincipal() + "]的密码不正确";
            log.error(msg);
            redirect.addFlashAttribute(MSG, msg);
        } catch (LockedAccountException lae) {
            String msg = "用户["+ token.getPrincipal() +"]被锁定了 ";
            log.error(msg);
            redirect.addFlashAttribute(MSG, msg);
        } catch (AuthenticationException ae) {
            String msg = ae.getMessage();
            log.error(msg);
            redirect.addFlashAttribute(MSG, msg);
        }
		return redirect("");
	}
	
	/**
	 * 跳转首页
	 * @RequiresAuthentication 验证用户是否登录，只能登录后才能访问该方法
	 * @param model
	 * @return
	 */
	@RequiresAuthentication
	@RequestMapping("/a/index")
	public String index(Model model){
		
		List<Menu> list3 = new ArrayList<Menu>();
		
		String username = SecurityUtils.getSubject().getPrincipal().toString();
		User user = userService.getOne(new QueryWrapper<User>().eq("user_name", username));
		
		List<UserRole> list2 = userRoleService.list(new QueryWrapper<UserRole>().eq("user_id", user.getId()));
		
		List<String> roleIds = new ArrayList<String>();
		for (UserRole userrole : list2) {
			roleIds.add(userrole.getRoleId());
		}
		
		if (!roleIds.isEmpty()) {
			List<RoleMenu> list = roleMenuService.list(new QueryWrapper<RoleMenu>().in("role_id", roleIds));
			
			List<String> menuIds = new ArrayList<String>();
			for (RoleMenu rolemenu : list) {
				menuIds.add(rolemenu.getMenuId());
			}
			
			if (!menuIds.isEmpty()) {
				list3 = menuService.list(new QueryWrapper<Menu>().in("id", menuIds).eq("menu_type", 1));
				findChildrens(list3, menuIds);
			}
		}
		model.addAttribute("list", list3);
		return disPlay(ADMIN, INDEX);
	}
	
	/**
	 * 左侧菜单递归查找
	 * @param list
	 * @param menuIds
	 */
	private void findChildrens(List<Menu> list, List<String> menuIds){
		for (Menu menu : list) {
			List<Menu> list2 = menuService.list(new QueryWrapper<Menu>().in("id", menuIds).eq("pid", menu.getId()));
			if (list2!=null && !list2.isEmpty()) {
				menu.setNodes(list2);
				findChildrens(list2, menuIds);
			}
		}
	}
}
